<template>
	<cl-crud ref="crud" @load="onLoad" :on-refresh="onRefresh">
		<cl-pagefull @resize="onResize">
			<template #head>
				<el-row>
					<cl-title-module
						title="总报表"
						:columns="initColumns"
						:print="printParams"
						v-model="table.columns"
						@export-file="exportExcel"
					/>
				</el-row>
				<el-row type="flex">
					<cl-filter-group v-model="search">
						<cl-filter label="所属事业部">
							<cl-select
								v-model="search.biz_id"
								placeholder="请选择"
								filterable
								@change="changeBiz"
								style="width: 150px"
							>
								<el-option
									v-for="item in business"
									:key="item.biz_id"
									:label="item.biz_name"
									:value="item.biz_id"
								/>
							</cl-select>
						</cl-filter>
						<cl-filter label="分公司">
							<cl-select
								v-model="search.company_id"
								placeholder="请选择"
								clearable
								filterable
								style="width: 150px"
								@change="refresh"
							>
								<el-option label="全部" value="" />

								<el-option
									v-for="item in bizRefData.company"
									:key="item.company_id"
									:label="item.company_name"
									:value="item.company_id"
								/>
							</cl-select>
						</cl-filter>
						<cl-filter label="品牌">
							<cl-select
								v-model="search.bra_id"
								placeholder="全部"
								clearable
								filterable
								multiple
								collapse-tags
								style="width: 150px"
								@change="refresh"
							>
								<el-option
									v-for="item in bizRefData.brand"
									:key="item.bra_id"
									:label="item.bra_name"
									:value="item.bra_id"
								/>
							</cl-select>
						</cl-filter>
						<cl-filter label="消费时间">
							<cl-date-picker
								v-model="search.date"
								type="daterange"
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								value-format="yyyy-MM-dd"
								:clearable="false"
								style="width: 210px"
								@change="refresh"
							/>
						</cl-filter>
						<cl-filter label="所属城市">
							<cl-select
								v-model="search.city_id"
								style="width: 100%"
								placeholder="请选择城市"
								multiple
								collapse-tags
								filterable
							>
								<el-option
									:label="item.label"
									:value="item.id"
									v-for="(item, index) in cityList"
									:key="index"
								/>
							</cl-select>
						</cl-filter>
						<cl-filter label="所属门店">
							<cl-shop-select
								v-model="search.dept_id"
								placeholder="请选择"
								filterable
								clearable
								style="width: 150px"
								@change="refresh"
								show-all
								:biz_id="search.biz_id"
							/>
						</cl-filter>
						<cl-filter label="战区">
							<cl-cascader
								clearable
								v-model="search.appoint_dept_id"
								:options="zone"
								:props="{
									value: 'dept_id',
									label: 'dept_name',
									checkStrictly: true
								}"
								filterable
								@change="changeAppointDept"
							/>
						</cl-filter>
						<cl-filter label="营业状态">
							<cl-select
								v-model="search.bus_state"
								style="width: 100%"
								placeholder="请选择营业状态"
							>
								<el-option
									label="全部"
									value="0"
									key="0"
								/>
								<el-option
									label="营业"
									value="1"
									key="1"
								/>
								<el-option
									label="停业"
									value="2"
									key="2"
								/>
							</cl-select>
						</cl-filter>
					</cl-filter-group>
				</el-row>
			</template>

			<el-row v-loading="loading">
				<!-- 数据表格 -->
				<zm-table id="summaryReport" v-bind="table" :data="list">
					<template #column-dept_name="{ scope: { row } }">
						<!-- <div > -->
							<span style="overflow-wrap: break-word;white-space: normal;">{{ row.dept_name }}</span>
						<!-- </div> -->
					</template>
				</zm-table>
			</el-row>
		</cl-pagefull>
	</cl-crud>
</template>
<script>
import { exportExcel } from "@/utils/excel";
import dayjs from "dayjs";
export default {
	name: "FinanceSummaryReport",
	data() {
		return {
			printParams: {
				id: "summaryReport",
				popTitle: "总报表"
			},
			// 表格配置
			table: {
				"context-menu": ["refresh"],
				columns: [],
				props: {
					"row-key": "dept_id",
					showSummary: true,
					summaryMethod: this.getSummaries,
					maxHeight: 500,
					defaultExpandAll: true
				}
			},
			initColumns: [
				// { label: "序号", type: "index", width: 50, fixed: true, disable: true },
				// { label: "日期", prop: "date", minWidth: 100, fixed: true },
				// {
				// 	label: "所属事业部",
				// 	prop: "biz_name",
				// 	minWidth: 150,
				// 	fixed: true,
				// 	align: "left",
				// 	showOverflowTooltip: true
				// },
				{
					label: "门店",
					prop: "dept_name",
					minWidth: 110,
					fixed: true,
					align: "left",
					showOverflowTooltip: true
				},
				// {
                //     label: "城市",
				// 	prop: "city_name",
				// 	minWidth: 150,
				// 	showOverflowTooltip: true
				// },
				{
                    label: "排客目标",
					prop: "goal_arrive",
					minWidth: 80,
					showOverflowTooltip: true
				},
				{
                    label: "排新客数",
					prop: "new_plan_arrive",
					minWidth: 80,
					showOverflowTooltip: true,
					sortable: true
				},
				{
                    label: "排老客数",
					prop: "old_plan_arrive",
					minWidth: 80,
					showOverflowTooltip: true,
					sortable: true
				},
				{
                    label: "总排客数",
					prop: "plan_arrive",
					minWidth: 80,
					showOverflowTooltip: true,
					sortable: true
				},
				{
                    label: "总排客率",
					prop: "plan_arrive_ratio",
					minWidth: 80,
					showOverflowTooltip: true,
					sortable: true
				},
				{
                    label: "到店人数",
                    children: [
                        { label: "新客数", prop: "new_lost_arrive", width: 100, sortable: true },
                        { label: "老客数", prop: "old_cart_arrived", width: 100, sortable: true },
						{ label: "总客数", prop: "total_cart_arrived", width: 100, sortable: true },
						{ label: "总到店率", prop: "cart_arrived_ratio", width: 100, sortable: true },
                    ]
                },
                {
                    label: "消费人数",
                    children: [
                        { label: "新客数", prop: "new_arrive", width: 100, sortable: true },
                        { label: "老客数", prop: "old_new_arrive", width: 100, sortable: true },
                        // { label: "老转新", prop: "old_new_arrive", width: 100, sortable: true },
                        { label: "总客数", prop: "total_arrive", width: 100, sortable: true },
                        { label: "退款人数", prop: "refund_people", width: 100, sortable: true },
                    ]
                },
				{
					label: "流失人数",
					width: 80,
					prop: "lost",
					sortable: true
				},
				{
					label: "流失率",
					width: 80,
					prop: "lost_rate"
				},
				{
                    label: "业绩",
                    children: [
                        {
                            label: "新客业绩",
                            width: 120,
                            prop: "new_achieve",
							sortable: true
                        },
                        {
                            label: "老客业绩",
                            width: 120,
                            prop: "old_new_achieve",
							sortable: true
                        },
						{
							label: "老带新业绩",
							width: 120,
							prop: "achieve_companion",
							sortable: true
						},
                        {
                            label: "总业绩",
                            width: 120,
                            prop: "total_achieve",
							sortable: true
                        },
                    ]
                },
				{
					label: "退款业绩",
					width: 120,
					prop: "refund_achieve",
					sortable: true
				},
				{
					label: "退款率",
					width: 120,
					prop: "refund_people_ratio",
					sortable: true
				},
				{
					label: "退款占比",
					width: 120,
					prop: "refund_achieve_ratio",
					sortable: true
				},
                {
                    label: "客单",
                    children: [
                        { label: "新客客单", prop: "new_price", width: 100, sortable: true },
                        { label: "老客客单", prop: "old_new_price", width: 100, sortable: true },
                        { label: "总客单", prop: "total_price", width: 100, sortable: true }
                    ]
                },
				{
					label: "定金人数",
					width: 80,
					prop: "deposit"
				},
				{
					label: "未到店人数",
					width: 80,
					prop: "no_arrive"
				}
			],
			list: [],
			cityList: [],
			search: {
				dept_id: "", //门店名称
				biz_id: "", //事业部
				company_id: "",
				bra_id: [],
				city_id: [],
				date: [
					dayjs()
						.startOf("day")
						.format("YYYY-MM-DD"),
					dayjs()
						.endOf("day")
						.format("YYYY-MM-DD")
				], //时间
				begin_time: "", //开始时间
				end_time: "", //结束时间
				bus_state: "0",
				first_zone_id: "",
				war_zone_id: ""
			},
			load: false,
			loading: false,
			zone:[]
		};
	},
	computed: {
		bizRefData() {
			let { biz_id } = this.search;
			return this.getBizRefData(biz_id);
		}
	},
	created() {
		const { initColumns } = this;
		this.table.columns = initColumns;
		this.search.biz_id = this.getCurrBiz();
		this.init();
	},
	methods: {
		onResize(h) {
			this.table.props.maxHeight = h;
		},
		onLoad({ ctx, app }) {
			ctx.service(this.$service.finance)
				.set("dict", {
					api: {
						page: "zoneReport"
					}
				})
				.done();
			app.refresh(this.search);
		},
		// crud刷新
		refresh() {
			this.$refs.crud.refresh({ page: 1, ...this.search });
		},
		async onRefresh(params, { next, render }) {
			this.loading = true;
			const data = await next(params).finally(() => {
				this.loading = false;
			});
			this.list = data;
			render(data);
		},
		//打印
		exportExcel() {
			exportExcel("#summaryReport");
		},
		async init() {
			const { biz_id } = this.search;
			this.getBizRefCompany(biz_id);
			this.getBizRefBrand(biz_id);
			this.getBizRefShop(biz_id);
			this.getcityList();
			this.getFirstZone();
		},
		changeBiz() {
			this.search = {
				...this.search,
				company_id: "",
				bra_id: [],
				city_id: [],
				dept_id: ""
			};
			this.init();
			this.refresh();
		},
		// 表格合计
		getSummaries({ columns, data }) {
			let ignore = ["date", "biz_name", "city_name", "dept_name"];
			let new_achieve = 0,
				old_new_achieve = 0,
				total_achieve = 0,
                new_arrive = 0,                
                old_arrive = 0,                
				old_new_arrive = 0,
				total_arrive = 0,
                lost = 0,
                deposit = 0,
                goal_arrive = 0,
                plan_arrive = 0,
                total_cart_arrived = 0,
                refund_achieve = 0,
                refund_people = 0,
                no_arrive = 0;
			return columns.map((column, index) => {
				if (index === 0) {
					return "合计";
				}
				if (ignore.includes(column.property)) return "";
				if (column.property == "plan_arrive_ratio") {
					if (goal_arrive) {
						let result = plan_arrive / goal_arrive;
						return this.toFixed(result * 100) + "%";
					} else {
						return 0;
					}
				}
				if (column.property == "cart_arrived_ratio") {
					if (plan_arrive) {
						let result = total_cart_arrived / plan_arrive;
						return this.toFixed(result * 100) + "%";
					} else {
						return 0;
					}
				}
				if (column.property == "refund_people_ratio") {
					if (total_arrive) {
						let result = refund_people / total_arrive;
						return this.toFixed(result * 100) + "%";
					} else {
						return 0;
					}
				}
				if (column.property == "refund_achieve_ratio") {
					if (total_achieve) {
						let result = refund_achieve / total_achieve;
						return this.toFixed(result * 100) + "%";
					} else {
						return 0;
					}
				}
				if (column.property == "new_price") {
					if ((new_arrive + lost) > 0) {
						let result = new_achieve / (new_arrive + lost);
						return this.toFixed(result);
					} else {
						return 0;
					}
				}
				if (column.property == "old_new_price") {
					if (old_new_arrive) {
						let result = old_new_achieve / old_new_arrive;
						return this.toFixed(result);
					} else {
						return 0;
					}
				}
				if (column.property == "total_price") {
					if ((new_arrive + lost) > 0) {
						let result = total_achieve / (new_arrive+lost);
						return this.toFixed(result);
					} else {
						return 0;
					}
				}
				if (column.property == "lost_rate") {
					if (lost + new_arrive) {
						let result = lost / (lost + new_arrive);
						return this.toFixed(result * 100) + "%";
					} else {
						return 0 + "%";
					}
				}

				const values = data.map(item => Number(item[column.property]));
				let sum = values.reduce((prev, curr) => {
					const value = Number(curr);
					if (!isNaN(value)) {
						return prev + curr;
					}
					return prev;
				}, 0);
				if (column.property == "goal_arrive") {
					goal_arrive = sum;
				}
				if (column.property == "refund_achieve") {
					refund_achieve = sum;
				}
				if (column.property == "refund_people") {
					refund_people = sum;
				}
				if (column.property == "plan_arrive") {
					plan_arrive = sum;
				}
				if (column.property == "total_cart_arrived") {
					total_cart_arrived = sum;
				}
				if (column.property == "new_achieve") {
					new_achieve = sum;
				}
				if (column.property == "old_new_achieve") {
					old_new_achieve = sum;
				}
				if (column.property == "total_achieve") {
					total_achieve = sum;
				}
				if (column.property == "new_arrive") {
					new_arrive = sum;
				}
				if (column.property == "old_arrive") {
					old_arrive = sum;
				}
				if (column.property == "old_new_arrive") {
					old_new_arrive = sum;
				}
				if (column.property == "total_arrive") {
					total_arrive = sum;
				}
				if (column.property == "lost") {
					lost = sum;
				}
				if (column.property == "deposit") {
					deposit = sum;
				}
				if (column.property == "no_arrive") {
					no_arrive = sum;
				}

				return this.toFixed(sum);
			});
		},
		//获取城市列表
		async getcityList() {
			const { biz_id, bra_id } = this.search;
			this.$service.spread.newGetbizcity({ biz_id, bra_id }).then(data => {
				let list = (data || []).map(v => ({ ...v, label: v.name, value: v.id }));
				this.cityList = list;
			});
		},
		async getFirstZone() {
			const { biz_id } = this.search;
			this.zone = await this.$service.dept.preDept({
				parent_id: 0,
				biz_id,
				post: 7
			});
         
            
		},
		changeAppointDept(e) {
			this.search.first_zone_id = e[0]
			this.search.war_zone_id = e[1] || ""
		}
	}
};
</script>
<style lang="scss" scoped>
::v-deep {
	.el-table {
		width: 99.9% !important;
	}
	.el-table--scrollable-x {
		.el-table__body-wrapper {
			z-index: 2;
		}
	}
}
</style>
